#include "minecraftblockinstancing.h"

MineCraftBlockInstancing::MineCraftBlockInstancing()
{

}

BlockMeta::BlockType MineCraftBlockInstancing::type() const
{
    return m_type;
}

void MineCraftBlockInstancing::setType(const BlockMeta::BlockType &newType)
{
    if (m_type == newType)
        return;
    m_type = newType;
    m_dirty = true;
    markDirty();
    emit typeChanged();
}

MineCraftSceneData *MineCraftBlockInstancing::scene() const
{
    return m_scene;
}

void MineCraftBlockInstancing::setScene(MineCraftSceneData *newScene)
{
    if (m_scene == newScene)
        return;
    m_scene = newScene;
    m_dirty = true;
    markDirty();
    emit sceneChanged();
}

QByteArray MineCraftBlockInstancing::getInstanceBuffer(int *instanceCount)
{
    QByteArray ret;

    if(m_dirty)
    {
        m_buffer = {};
        m_instanceCount = 0;
        if(m_scene && m_type != BlockMeta::None)
        {
            auto ext = m_scene->extend();

            for(int x = 0;x < ext.x();x ++ )
            {
                for(int y = 0;y < ext.x();y ++ )
                {
                    for(int z = 0;z < ext.x();z ++ )
                    {
                        auto block = m_scene->get(x,y,z);

                        if(!block)
                        {
                            continue;
                        }

                        if(block->type != m_type)
                        {
                            continue;
                        }

                        QVector3D position(x * 100 + 50,y * 100 + 50,z * 100 + 50),rotation;
                        rotation = block->rotation;
                        auto entry = calculateTableEntry(position,{1,1,1},rotation,Qt::white);
                        m_buffer.append(reinterpret_cast<const char *>(&entry), sizeof(entry));
                        m_instanceCount++;
                    }
                }
            }


        }



        m_dirty = false;
    }

    *instanceCount = m_instanceCount;
    return m_buffer;
}
